package com.epam.DAO.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.TypedQuery;

import com.epam.DAO.BillDAO;
import com.epam.entity.Bill;
import com.epam.entity.Client;
import com.epam.entity.Request;
import com.epam.entity.Status;
import com.epam.utils.Interceptor;

@Interceptors(Interceptor.class)
@Stateless
public class BillDAOImpl extends GenericDAOImpl<Bill> implements BillDAO {

	public BillDAOImpl() {
		super(Bill.class);
	}

	@Override
	public List<Bill> getUserBills(Client client, int first, int size,
			Status... status) {

		StringBuffer queryString = new StringBuffer(
				"SELECT DISTINCT b FROM Bill b "
						+ "WHERE b.request.client = :client AND b.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR b.status = ?" + i);
		}
		TypedQuery<Bill> query = em.createQuery(queryString.toString(),
				Bill.class);
		query.setParameter("client", client);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Bill> list = query.setMaxResults(size).setFirstResult(first).getResultList();
		return list;
	}

	@Override
	public int getUserBillsCount(Client client, Status... status) {
		StringBuffer queryString = new StringBuffer(
				"SELECT DISTINCT b FROM Bill b "
						+ "WHERE b.request.client = :client AND b.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR b.status = ?" + i);
		}
		TypedQuery<Bill> query = em.createQuery(queryString.toString(),
				Bill.class);
		query.setParameter("client", client);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Bill> list = query.getResultList();
		return list.size();
	}

	@Override
	public List<Bill> getRequestBills(Request request) {
		TypedQuery<Bill> query = em.createQuery(
				"SELECT DISTINCT b FROM Bill b WHERE b.request = :request",
				Bill.class).setParameter("request", request);
		List<Bill> list = query.getResultList();
		return list;
	}

}
